package com.store.app.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.OneYuanBuyUpdateBean;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;
import com.store.app.utils.UtilsBitmap;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;

import org.json.JSONObject;

import java.io.File;
import java.util.Date;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/12/10.
 * 创建活动(刮刮乐)
 */
public class CreateGGLActivity extends BaseActivity implements View.OnClickListener ,IOnHttpListener{
    private ImageView public_ll_return;
    private TextView tvTitle;
    private EditText et_activity_name;
    private EditText et_goods_name;
    private EditText et_goods_price;
    private TextView tv_submit;
    private ImageView iv_add_pic;
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static String localTempImageFileName = "";
    private Dialog dialog;
    private BitmapBean bitmapBean;
    private NetRequest netRequest;
    private String doc_id;
    private String title;
    private String award_value;
    private String award_name;
    private String pic;
    private String pic_id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_activity);

        initView();
        initData();
        ExitApplication.getInstance().addActivity(this);

    }


    private void initData(){
        netRequest = new NetRequest(this);

        if(getIntent()!=null){
            if(getIntent().getStringExtra("title")!=null){
                et_activity_name.setText(getIntent().getStringExtra("title"));
                et_goods_name.setText(getIntent().getStringExtra("award_name"));
                et_goods_price.setText(getIntent().getStringExtra("award_value"));
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .cacheInMemory(true)
                        .showImageOnLoading(R.drawable.default_picture_s)
                        .showImageOnFail(R.drawable.default_picture_s)
                        .showStubImage(R.drawable.default_picture_s)
                        .imageScaleType(ImageScaleType.EXACTLY)
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .build();
                pic_id = getIntent().getStringExtra("pic_id");
                doc_id = pic_id;
                ImageLoader.getInstance().displayImage(getIntent().getStringExtra("pic"), iv_add_pic, options);
            }
        }
    }

    private void initView() {
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("刮刮乐");
        et_activity_name = (EditText) findViewById(R.id.et_activity_name);
        et_goods_name = (EditText) findViewById(R.id.et_goods_name);
        et_goods_price = (EditText) findViewById(R.id.et_goods_price);
        tv_submit = (TextView) findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(this);
        iv_add_pic = (ImageView) findViewById(R.id.iv_add_pic);
        iv_add_pic.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_submit:
                submit();
                break;
            case R.id.iv_add_pic:
                getPic();
                break;
            case R.id.public_ll_return:
                finish();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    CropUtils.startCropActivity(uri, CreateGGLActivity.this, 5, 5);
                }
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {
            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            if (uri != null) {
                UtilsBitmap.getCompressUri(uri);
                CropUtils.startCropActivity(uri, CreateGGLActivity.this, 5, 5);
            }
        }
        //拿到裁剪后的图片
        if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                bitmapBean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);
                if (bitmapBean.getIsBm() != null) {
                    //上传图片
                    netRequest.requestUploadPic(1, bitmapBean.getIsBm());
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            Toast.makeText(CreateGGLActivity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        }

    }


    public void getPic() {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        dialog = new AlertDialog.Builder(CreateGGLActivity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);
                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status
                                            .equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            Uri u = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    u);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                        }
                                    }
                                }
                            }
                        }).show();
    }
    private void submit() {
        if(Utils.isFastClick()){
            return;
        }
        // validate
        String name = et_activity_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入活动名称", Toast.LENGTH_SHORT).show();
            return;
        }

        String goods_name = et_goods_name.getText().toString().trim();
        if (TextUtils.isEmpty(goods_name)) {
            Toast.makeText(this, "请输入商品名称", Toast.LENGTH_SHORT).show();
            return;
        }

        String price = et_goods_price.getText().toString().trim();
        if (TextUtils.isEmpty(price)) {
            Toast.makeText(this, "请输入商品价格", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(doc_id)){
            Toast.makeText(this, "请上传图片", Toast.LENGTH_SHORT).show();
            return;
        }
        showProgressDialog("创建刮刮乐", "提交中……", true);
        netRequest.requestCreateActivityGGL(2,name,goods_name,MoneyUtil.formatMoney(price),doc_id);
    }

    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
        ToastTools.showShort(CreateGGLActivity.this,"请检查本地网络");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();
        if(requestId == 1){
            try {
                JSONObject object = new JSONObject(result);
                doc_id = object.getString("doc_id");
                iv_add_pic.setImageBitmap(bitmapBean.getBitmap());
            }catch (Exception e){

            }
        }
        else if(requestId == 2){
            ToastUtils.showTextToast(CreateGGLActivity.this,"发布成功！");
            //通知一元抽奖页面刷新
            EventBus.getDefault().post(new OneYuanBuyUpdateBean(1));
            EventBus.getDefault().post(new EventBusBean(203));
            finish();
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        dismissProgressDialog();
        ToastTools.showShort(CreateGGLActivity.this,msg);
    }
}
